package com.zzty.daoimpl;

import com.zzty.common.DBUtil;
import com.zzty.common.DBUtilPool;
import com.zzty.dao.QuestionDao;
import com.zzty.entity.Question;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


public  class QuestionDaoImpl implements QuestionDao {


    public Integer insertContent(String content) {
        Integer questionId=null;
        try {
            Connection cn =DBUtilPool.getConnection();
            PreparedStatement pst=
                    cn.prepareStatement("insert into question(content) values(?)");
            pst.setString(1,content);
            Integer count=pst.executeUpdate();
            if(count==1) {
                PreparedStatement pst1=
                        cn.prepareStatement("select IFNULL(MAX(id),0 ) as id from question");
                ResultSet rs = pst1.executeQuery();
                while (rs.next()) {
                    questionId = rs.getInt("id");
                }
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return questionId==null?null:questionId;
    }


    public String getContentById(Integer id) {
        String content=null;
        try {
            Connection cn =DBUtilPool.getConnection();
            PreparedStatement pst=
                    cn.prepareStatement("select * from question where id=?");
            pst.setInt(1,id);
            ResultSet rs=pst.executeQuery();
            while(rs.next()){
                content=rs.getString("content");
            }
            DBUtilPool.releaseConnection(cn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content==null?null:content;
    }

    @Override
    public List getQuestionsToTable() {
        List<Question>questions=null;
        try {
            Connection cn =DBUtilPool.getConnection();
            PreparedStatement pst=
                    cn.prepareStatement("select * from question");
            ResultSet rs = pst.executeQuery();
            while(rs.next()){
                if(questions==null){
                    questions =new ArrayList<>();
                }
                Question question = new Question();
                question.setId(rs.getInt("id"));
                question.setContent(rs.getString("content"));
                questions.add(question);
            }
            DBUtilPool.releaseConnection(cn);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return questions==null?null:questions;
    }
}
